﻿
Imports System.Drawing.Printing

Public Class FrTransactions
    Private EmployeeID As String
    Private LostCard As Boolean
    Private content As String
    Private row As DataGridViewRow
    Public cardNumber As String
    Public _TotalofDay As Integer = getOptions("TotalOfday")
    Public _Color As Byte = getOptions("color")
    Public _Port As String = getOptions("port")
    Public _Header As String = getOptions("header")
    Public _Footer As String = getOptions("footer")
    Public _autoOrder As Byte = getOptions("order")
    Public _defaultPrint As Byte = getOptions("Print")
    Public _getlastcard As String = getLastCardSQL()
    Public Timeout As Integer = getOptions("Timeout")
    Public reprint As String
    Private lastconfirm As Date

    Private Sub TimerT_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerT.Tick

        Dim isPrintSuccessfully As Boolean = False
        'Dim CardNumber As String = ""
        cardNumber = ""

        Dim dt As DataTable
        ' Doc thong tin the

        TimerT.Enabled = False 'Ngung doc the
        If chkStart.Checked Then
            Try
                cardNumber = getLastCard(_getlastcard)
            Catch ex As Exception
                db.iscardServer = False
                MsgBox(ex.Message)

            End Try
        End If


        If LostCard Then
            GoTo lostCardLB
        End If
        'Neu tim thay Card Number (Quet the)
        If cardNumber.Length <= 0 Then
            GoTo EndSub
        End If
        dt = db.getvalue("select * from CardNumber where CardNumberID = '" & cardNumber & "'").Tables(0)
        '1. Old Card Number
        If dt.Rows.Count > 0 Then
            'a. Neu Card Number bi disable-->Enable
            If Not dt.Rows(0).Item("cActive") Then
                PrintError("04") 'The bi khoa
                'dlgCard.txtFind.Text = CardNumber
                'dlgCard.FindByCardNumber()
                'dlgCard.ShowDialog()
                GoTo EndSub
            End If
            'b. Neu Card Number Enable-->3.
        Else
            '2. New Card Number
            'If MsgBox("Do you want to save new Card Number?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then


            '    '2.1 Add CardNumber(active) to database
            db.update("insert into CardNumber(CardNumberID,cActive,cCreatedby) " _
            & " values('" & cardNumber & "',1,'" & LoginForm.userID & "')")
            '    '2.2 List Employee chua co CardNumber de map
            '    MapCardNumber(CardNumber)
            'Else
            '    GoTo EndSub
            'End If
            PrintError("03") ' the la
            GoTo EndSub
        End If

        'Yeu cau quet the lai

        '3. Tim Employee ID theo Card Number
        EmployeeID = db.getvalue("select * from Employee where eCardNumber ='" & cardNumber & "' ", "EmployeeID")

lostCardLB:
        If db.getvalue("select * from employee where eactive=1 and Employeeid = '" & EmployeeID & "'", "EmployeeID") = "" Then
            PrintError("06") 'employee bi disable
            GoTo EndSub
        End If



        '3.1 Neu Tim thay card Number
        If EmployeeID <> "" Then
            Dim total As Double
            Dim eTotalOfDay As String
            total = TotalOfDay(EmployeeID)
            eTotalOfDay = db.getvalue("select * from eTotalOfDay where employeeID = '" & EmployeeID & "'", "TotalOfDay")

            If eTotalOfDay <> "" Then
                If total >= eTotalOfDay Then
                    PrintError("01")
                    GoTo EndSub
                End If
            Else
                If total >= _TotalofDay Then
                    PrintError("01")
                    GoTo EndSub
                End If
            End If

            Dim t As Date = Now()

            DlgOrder.employeeID = EmployeeID
            'DlgOrder.Visible = CBool(db.getvalue("select * from options where oname = 'Order'", "ovalue"))

            If DlgOrder.ShowDialog = Windows.Forms.DialogResult.OK Then
                Dim lastrow, lastORD As Integer
                Dim card As String
                If DlgOrder.LeftCoupon <> "No limit" Then
                    If DlgOrder.LeftCoupon < 0 Then
                        PrintError("02")
                        GoTo EndSub
                    End If
                End If
                card = db.getvalue("select * from Employee where employeeID = '" & DlgOrder.employeeID & "'", "eCardNumber")
                lastORD = "0" & db.getvalue("select * from transactions where year(tdate) = year(getdate()) and month(tdate) = month(getdate()) and day(tdate) = day(getdate()) order by stt desc", "stt")
                ''View Transactions

                lastrow = dgvT.Rows.Count
                dgvT.Rows.Insert(lastrow)
                dgvT.Item("OrdinalNumber", lastrow).Value = lastORD + 1
                dgvT.Item("TransactionID", lastrow).Value = t.Year & FillSpace(t.Month, 2, 0, "0", "LEFT") & FillSpace(t.Day, 2, 0, "0", "LEFT") & FillSpace(t.Hour, 2, 0, "0", "LEFT") & FillSpace(t.Minute, 2, 0, "0", "LEFT") & FillSpace(t.Second, 2, 0, "0", "LEFT")
                dgvT.Item("EmployeeID", lastrow).Value = DlgOrder.employeeID
                dgvT.Item("FullName", lastrow).Value = DlgOrder.txtFullName.Text
                dgvT.Item("CardNumber", lastrow).Value = card
                dgvT.Item("Coupon", lastrow).Value = DlgOrder.Coupon
                dgvT.Item("Quantity", lastrow).Value = DlgOrder.Quantity
                dgvT.Item("Created by", lastrow).Value = IIf(LostCard, LoginForm.userID, "System")
                dgvT.Item("Date", lastrow).Value = t
                dgvT.Item("Action", lastrow).Value = "Print"
                dgvT.Item("action", lastrow).Style.ForeColor = Color.Blue
                ''''Print
                row = dgvT.Rows(lastrow)
                If DlgOrder.print Then
                    isPrintSuccessfully = PrintTicket(row, True)
                    'PrintTicket(True)
                End If
                'LostCard = False
                'dgvT.Item(dgvT.Columns.Count - 1, lastrow).Value = "Print"
                'Insert database for this Transactions
                If Not cbtest.Checked And isPrintSuccessfully Then

                    Dim sql As String
                    sql = "insert into Transactions(stt,transactionID,EmployeeID,CardNumber,Coupon,tQuantity,tCreatedby,tDate,tprint) " _
                        & " Values(" & dgvT.Item("OrdinalNumber", lastrow).Value _
                        & ",'" & dgvT.Item("TransactionID", lastrow).Value _
                        & "','" & dgvT.Item("EmployeeID", lastrow).Value _
                        & "','" & card _
                        & "','" & dgvT.Item("Coupon", lastrow).Value _
                        & "'," & dgvT.Item("Quantity", lastrow).Value _
                        & ",'" & dgvT.Item("Created by", lastrow).Value _
                        & "','" & dgvT.Item("Date", lastrow).Value _
                        & "'," & DlgOrder.print * -1 & ")"
                    db.update(sql)
                    dgvT.Item("action", lastrow).Style.ForeColor = Color.Black
                End If
            End If
            EmployeeID = ""

        Else
            '3.2 CardNumber active but chua duoc map
            'MapCardNumber(CardNumber)
            PrintError("05")
            GoTo EndSub

        End If
EndSub:
        LostCard = False
        TimerT.Enabled = True 'Tiep tuc doc the
    End Sub
    Private Sub MapCardNumber(ByVal CardNumber As String)
        dlgMapCardNumber.CardNumber = CardNumber
        dlgMapCardNumber.ShowDialog()
    End Sub

    Private Sub Transactions_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        TimerT.Enabled = False
        Me.Dispose()
    End Sub


    Private Sub FrTransactions_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
        If e.Control = True And e.KeyCode = Keys.F Then
            btnLostCard_Click(sender, e)
        End If
    End Sub



    Private Sub Transactions_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        TimerT.Enabled = True
        dgvT.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        dgvT.Columns.Add("OrdinalNumber", "Ordinal")
        dgvT.Columns.Add("TransactionID", "Transactions ID")
        dgvT.Columns.Add("EmployeeID", "Employee ID")
        dgvT.Columns.Add("FullName", "Full Name")
        dgvT.Columns.Add("CardNumber", "Card Number")
        dgvT.Columns.Add("Coupon", "Coupon")
        dgvT.Columns.Add("Quantity", "Quantity")

        dgvT.Columns.Add("Created by", "Created by")
        dgvT.Columns.Add("Date", "Date")

        dgvT.Columns("OrdinalNumber").Width = 50
        dgvT.Columns("TransactionID").Width = 120
        dgvT.Columns("FullName").Width = 140
        dgvT.Columns("CardNumber").Width = 96
        dgvT.Columns("EmployeeID").Width = 92
        dgvT.Columns("Created by").Width = 84
        dgvT.Columns("Quantity").Width = 56
        dgvT.Columns("Quantity").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        dgvT.Columns("Date").Width = 140

        Dim dgBtnCol = New DataGridViewDisableButtonColumn()
        dgBtnCol.name = "Action"
        dgvT.Columns.Add(dgBtnCol)
        dgvT.Columns("Action").Width = 50
        Dim tb As DataTable
        tb = db.getvalue("select stt,TransactionID,EmployeeID,(select eFullName from employee where employeeID=transactions.EmployeeID) as FullName,CardNumber, Coupon,tQuantity as 'Quantity', tCreatedby as 'Created by',tdate as 'Date',tprint from transactions where year(tdate) = year(getdate()) and month(tdate) = month(getdate()) and day(tdate) = day(getdate()) order by stt").Tables(0)

        'dgvT.Columns(0).ValueType = GetType(String)
        For i As Integer = 0 To tb.Rows.Count - 1
            dgvT.Rows.Add()

            For j As Integer = 0 To tb.Columns.Count - 2
                dgvT.Item(j, i).Value = CStr(tb.Rows(i).Item(j))
            Next


            'dgvT.Item(0, i).ValueType = GetType(String)
            dgvT.Item(tb.Columns.Count - 1, i).Value = "Print"
            If tb.Rows(i).Item("tprint") > 1 Then
                dgvT.Item(tb.Columns.Count - 1, i).Value = "Print(" & tb.Rows(i).Item("tprint") - 1 & ")"
                'dgvT.Item(tb.Columns.Count - 1, i).Value &= " (Reprint)" ':" & tb.Rows(i).Item("tprint") - 1 & ")"
            End If
        Next
        dgvT.ReadOnly = True
        lastconfirm = Now()
    End Sub

    Private Sub btnLostCard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLostCard.Click
        'TimerT.Enabled = False
        If LoginForm.confirm And DateAdd(DateInterval.Second, Timeout, lastconfirm) < Now() Then
            If dlgCPass.ShowDialog = Windows.Forms.DialogResult.OK Then
                If dlgFindEmployee.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    EmployeeID = dlgFindEmployee.employeeID
                    LostCard = True
                End If

                lastconfirm = Now()
            End If
        Else
            'If dlgCPass.ShowDialog = Windows.Forms.DialogResult.OK Then
            If dlgFindEmployee.ShowDialog() = Windows.Forms.DialogResult.OK Then
                EmployeeID = dlgFindEmployee.employeeID
                LostCard = True
            End If
            'End If

            lastconfirm = Now()
        End If

        'TimerT.Enabled = True


    End Sub

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.




    End Sub

    Private Sub FrTransactions_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        dgvT.Width = Me.Width - dgvT.Location.X - 30
        dgvT.Height = Me.Height - dgvT.Location.Y - 50
        chkStart.Left = dgvT.Left + dgvT.Width - chkStart.Width
    End Sub


    Private Sub dgvT_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvT.CellContentClick
        If e.ColumnIndex = dgvT.Columns.Count - 1 And e.RowIndex > -1 Then
            'TimerT.Enabled = False
            If LoginForm.confirm And DateAdd(DateInterval.Second, Timeout, lastconfirm) < Now() Then
                If dlgCPass.ShowDialog = Windows.Forms.DialogResult.Cancel Then
                    Exit Sub
                End If
            End If
            If MsgBox("Are you sure to print?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                row = dgvT.Rows(e.RowIndex)
                reprint = ""
                'row.Cells("OrdinalNumber").Value = row.Cells("OrdinalNumber").Value.ToString.Replace(" (Reprint)", "")
                If db.getvalue("select * from transactions where transactionID='" & row.Cells("TransactionID").Value & "'", "Stt") > 0 Then

                    reprint = db.getvalue("select * from transactions where transactionID='" & row.Cells("TransactionID").Value & "'", "tprint")

                    'row.Cells("OrdinalNumber").Value &= " (Reprint:" & t & ")"

                End If
                'If LoginForm.confirm Then
                '    If dlgCPass.ShowDialog = Windows.Forms.DialogResult.OK Then

                '        print()
                '        db.update("update transactions set tprint = isnull(tprint,0) + 1 where transactionID='" & dgvT.Item("TransactionID", e.RowIndex).Value & "' ")
                '    End If
                'Else
                '    'row = dgvT.Rows(e.RowIndex)
                '    print()
                '    db.update("update transactions set tprint = isnull(tprint,0) + 1 where transactionID='" & dgvT.Item("TransactionID", e.RowIndex).Value & "' ")
                'End If
                PrintTicket(row, False)

                'PrintTicket(False)
                row.Cells("Action").Value = "Print(" & reprint & ")"
                db.update("update transactions set tprint = isnull(tprint,0) + 1 where transactionID='" & row.Cells("TransactionID").Value & "' ")
                row.Cells("Action").Style.ForeColor = Color.Black
                lastconfirm = Now()
            End If


            'TimerT.Enabled = True
        End If
    End Sub
    'status: true-> New; false->reprint
    Private Function PrintTicket(ByVal status As Boolean) As Boolean

        '++Chinh add try catch
        Try
            Dim f As New POSPrinter.U220POS

            f.openPrinter(_Port) 'db.getvalue("select * from options where oname = 'Port'", "ovalue")
            f.WriteString(_Header & Chr(13) & Chr(10), 0, 1, 1, _Color)
            f.WriteString("Ordinal: " & row.Cells("OrdinalNumber").Value & IIf(Len(reprint) > 0, " (Reprint:" & reprint & ")", ""), 1, 0, 0, _Color)
            f.WriteString("Date   : " & Format(Now(), "MMM dd yyyy, hh:mm tt"), 1, 0, 0, _Color)
            'f.WriteString("ID      : " & row.Cells("EmployeeID").Value, 1, 0, 0, _Color)
            f.WriteString("Name   : " & row.Cells("FullName").Value, 1, 0, 0, _Color)
            f.WriteString("Dept   : " & db.getvalue("select * from department where departmentid=(select edepartment from employee where employeeid='" & row.Cells("EmployeeID").Value & "')", "dep_name"), 1, 0, 0, _Color)
            f.WriteString("Card   : " & db.getvalue("select * from employee where employeeID = '" & row.Cells("EmployeeID").Value & "'", "eCardNumber"), 1, 0, 0, _Color)
            f.WriteString("Coupon : " & db.getvalue("select * from coupon where couponid = '" & row.Cells("Coupon").Value & "'", "Cname") & " (" & row.Cells("Quantity").Value & ")", 1, 0, 0, _Color)
            'f.WriteString("Quantity: " & row.Cells("Quantity").Value, 1, 0, 0, _Color)
            If status Then
                f.WriteString("Left   : " & LeftC(row.Cells("EmployeeID").Value, row.Cells("Coupon").Value, row.Cells("Quantity").Value), 1, 0, 0, _Color)
            Else
                f.WriteString("Left   : " & LeftC(row.Cells("EmployeeID").Value, row.Cells("Coupon").Value, 0), 1, 0, 0, _Color)
            End If

            f.WriteString(_Footer, 0, 0, 1, _Color)
            f.closePrinter()
            reprint = ""
            Return True
        Catch ex As Exception
            reprint = ""
            Return False
        End Try
        '--Chinh add try catch
    End Function
    'status: true-> New; false->reprint
    Private Function PrintTicket(ByVal row As DataGridViewRow, ByVal status As Boolean) As Boolean

        '++Chinh add try catch
        Try
            Dim f As New POSPrinter.U220POS

            f.openPrinter(_Port) 'db.getvalue("select * from options where oname = 'Port'", "ovalue")
            f.WriteString(_Header & Chr(13) & Chr(10), 0, 1, 1, _Color)
            f.WriteString("Ordinal: " & row.Cells("OrdinalNumber").Value & IIf(Len(reprint) > 0, " (Reprint:" & reprint & ")", ""), 1, 0, 0, _Color)
            f.WriteString("Date   : " & Format(Now(), "MMM dd yyyy, hh:mm tt"), 1, 0, 0, _Color)
            'f.WriteString("ID      : " & row.Cells("EmployeeID").Value, 1, 0, 0, _Color)
            f.WriteString("Name   : " & row.Cells("FullName").Value, 1, 0, 0, _Color)
            f.WriteString("Dept   : " & db.getvalue("select * from department where departmentid=(select edepartment from employee where employeeid='" & row.Cells("EmployeeID").Value & "')", "dep_name"), 1, 0, 0, _Color)
            f.WriteString("Card   : " & db.getvalue("select * from employee where employeeID = '" & row.Cells("EmployeeID").Value & "'", "eCardNumber"), 1, 0, 0, _Color)
            f.WriteString("Coupon : " & db.getvalue("select * from coupon where couponid = '" & row.Cells("Coupon").Value & "'", "Cname") & " (" & row.Cells("Quantity").Value & ")", 1, 0, 0, _Color)
            'f.WriteString("Quantity: " & row.Cells("Quantity").Value, 1, 0, 0, _Color)
            If status Then
                f.WriteString("Left   : " & LeftC(row.Cells("EmployeeID").Value, row.Cells("Coupon").Value, row.Cells("Quantity").Value), 1, 0, 0, _Color)
            Else
                f.WriteString("Left   : " & LeftC(row.Cells("EmployeeID").Value, row.Cells("Coupon").Value, 0), 1, 0, 0, _Color)
            End If

            f.WriteString(_Footer, 0, 0, 1, _Color)
            f.closePrinter()
            reprint = ""
            Return True
        Catch ex As Exception
            reprint = ""
            Return False
        End Try
        '--Chinh add try catch
    End Function
    Private Sub PrintError(ByVal err As String)

        Dim outto As Byte
        Dim errors As String
        Dim name As String = ""
        outto = db.getvalue("select * from options where oname = 'Errors'", "ovalue")
        errors = db.getvalue("select * from errors where eid = '" & err & "'", "edesc")
        If chkStart.Checked Then
            db.iscardServer = True
            name = db.getvalue("select fname + ' ' + lname as fullname from badge,badge_c where badge.id=badge_c.id and badge_c.cardno='" & cardNumber & "'", "fullname")

            db.iscardServer = False
        End If
        Select Case outto
            Case 0
                MsgBox("Name: " & name & Chr(13) & errors, MsgBoxStyle.Exclamation, "Information")
            Case 1
                Dim f As New POSPrinter.U220POS
                f.openPrinter(_Port)
                f.WriteString(_Header & Chr(13) & Chr(10), 0, 0, 1, _Color)
                f.WriteString("Name: " & name, 0, 0, 0, _Color)
                f.WriteString(formatErrors(errors, 0), 0, 0, 0, 1)
                f.closePrinter()

        End Select

    End Sub




    Private Sub print()

        Dim print_document As New PrintDocument
        print_document.PrinterSettings = FrMain.dlgPrint.PrinterSettings
        ' Install the PrintPage event handler.

        AddHandler print_document.PrintPage, AddressOf Print_PrintPage
        print_document.Print()


    End Sub
    ' Print the next page.
    Private Sub Print_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)

        Dim font As New Font("verdana", 9)
        Dim fontB As New Font("Verdana", 13)
        Dim fmt As New StringFormat(StringFormatFlags.NoClip)
        Dim l, t, a As Integer
        l = 0 'e.PageSettings.Margins.Left
        t = 0 'e.PageSettings.Margins.Top
        a = 60
        Dim pnt As New Point(l, t)
        DrawStringLine(e, "Unilever Vietnam", fontB, Brushes.Black, l + 30, t, fmt)

        t = 30

        DrawStringLine(e, "Ordinal", font, Brushes.Black, l, t, fmt)
        DrawStringLine(e, "Date", font, Brushes.Black, l, t, fmt)
        DrawStringLine(e, "ID", font, Brushes.Black, l, t, fmt)
        DrawStringLine(e, "Name", font, Brushes.Black, l, t, fmt)
        DrawStringLine(e, "Card", font, Brushes.Black, l, t, fmt)
        DrawStringLine(e, "Coupon", font, Brushes.Black, l, t, fmt)
        DrawStringLine(e, "Quantity", font, Brushes.Black, l, t, fmt)
        DrawStringLine(e, "Left", font, Brushes.Black, l, t, fmt)

        t = 30
        DrawStringLine(e, ": " & row.Cells("OrdinalNumber").Value, font, Brushes.Black, l + a, t, fmt)
        DrawStringLine(e, ": " & Format(Now(), "MMM dd, hh:mm tt"), font, Brushes.Black, l + a, t, fmt)
        DrawStringLine(e, ": " & row.Cells("EmployeeID").Value, font, Brushes.Black, l + a, t, fmt)
        DrawStringLine(e, ": " & row.Cells("FullName").Value, font, Brushes.Black, l + a, t, fmt)
        DrawStringLine(e, ": " & db.getvalue("select * from employee where employeeID = '" & row.Cells("EmployeeID").Value & "'", "eCardNumber"), font, Brushes.Black, l + a, t, fmt)
        DrawStringLine(e, ": " & db.getvalue("select * from coupon where couponid = '" & row.Cells("Coupon").Value & "'", "Cname"), font, Brushes.Black, l + a, t, fmt)
        DrawStringLine(e, ": " & row.Cells("Quantity").Value, font, Brushes.Black, l + a, t, fmt)
        DrawStringLine(e, ": " & LeftC(row.Cells("EmployeeID").Value, row.Cells("Coupon").Value, row.Cells("Quantity").Value), font, Brushes.Black, l + a, t, fmt)
        t = t + 10
        DrawStringLine(e, "Enjoy your meal !!!", font, Brushes.Black, l + 50, t, fmt)
        'Drawstringline(e,content, font, Brushes.Black, New Point(l, t), fmt)
    End Sub
    Private Sub DrawStringLine(ByVal e As System.Drawing.Printing.PrintPageEventArgs, ByVal s As String, ByVal font As Font, ByVal brush As Brush, ByVal x As Single, ByRef y As Single, ByVal fmt As StringFormat)
        e.Graphics.DrawString(s, font, brush, x, y)
        y = y + 15
    End Sub



    Private Sub chkStart_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkStart.CheckedChanged
        'TimerT.Enabled = chkStart.Checked

        chkStart.Text = IIf(chkStart.Checked, "Stop", "Start")


    End Sub

    Private Sub cbtest_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbtest.CheckedChanged
        'MsgBox(e.ToString)
        If cbtest.Checked Then
            If dlgCPass.ShowDialog <> Windows.Forms.DialogResult.OK Then
                'cbtest.Checked = True
                ' Else
                cbtest.Checked = False
            End If
        End If
    End Sub


    Private Sub cbtest_EnabledChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbtest.EnabledChanged
        MsgBox(e.ToString)
    End Sub
End Class


